package com.junyidao.game.service;

import com.alibaba.druid.support.json.JSONUtils;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.junyidao.game.Exception.BusinessException;
import com.junyidao.game.pay.AlipayAccount;
import com.junyidao.game.pay.AlipayConstant;
import com.junyidao.game.util.NumUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by zzh on 2016/9/26.
 * 文件描述 ：支付宝支付服务
 */
@Service
@Transactional
public class AlipayService {

    private static final Logger logger = LoggerFactory.getLogger(AlipayService.class);

    /**
     * 支付宝扫码支付生成二维码
     *
     * @param amount         订单总金额 本系统金额单位为分
     * @param outTradeNo     商户订单号,64个字符以内、只能包含字母、数字、下划线；需保证在商户端不重复
     * @param subject        订单标题
     * @param timeoutExpress 该笔订单允许的最晚付款时间，逾期将关闭交易
     * @return
     */
    public String getAlipayQRCode(Integer amount, String outTradeNo, String subject, String timeoutExpress) {
        Double total_amount = NumUtils.divide(amount, 100);
        //商户系统调用支付宝预下单接口alipay.trade.precreate，获得该订单二维码图片地址
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayAccount.ALIPAY_GATEWAY,
                AlipayAccount.APPID, AlipayAccount.APP_PRIVATE_KEY, "json", "UTF-8",
                AlipayAccount.ALIPAY_PUBLIC_KEY);
        //创建API对应的request类
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        Map<String, String> map = new HashMap<>();
        map.put("out_trade_no", outTradeNo);
        map.put("total_amount", total_amount.toString());
        map.put("subject", subject);
        map.put("timeout_express", timeoutExpress);
        request.setBizContent(JSONUtils.toJSONString(map));//设置业务参数
        System.out.printf("---------" + request.getBizContent());

        AlipayTradePrecreateResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            logger.error("支付宝扫码支付接口调用失败：", e);
        }
        String code = response.getCode();
        String msg = response.getSubMsg();
        if (!code.equals(AlipayConstant.PAY_SUCCESS)) {
            BusinessException.throwException(1, msg);
        }
        return response.getQrCode();
    }

    public AlipayTradeQueryResponse queryPayStatus(String outTradeNo) {
        //商户系统调用支付宝预下单接口alipay.trade.precreate，获得该订单二维码图片地址
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayAccount.ALIPAY_GATEWAY,
                AlipayAccount.APPID, AlipayAccount.APP_PRIVATE_KEY, "json", "UTF-8",
                AlipayAccount.ALIPAY_PUBLIC_KEY);
        //创建API对应的request类
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        Map<String, String> map = new HashMap<>();
        map.put("out_trade_no", outTradeNo);
        request.setBizContent(JSONUtils.toJSONString(map));//设置业务参数
        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            logger.error("支付宝扫码支付订单查询接口调用失败：工单号" + outTradeNo, e);
        }
        String code = response.getCode();
        String msg = response.getSubMsg();
        if (!code.equals(AlipayConstant.PAY_SUCCESS)) {
            BusinessException.throwException(1, msg);
        }
        return response;
    }

}
